const {
	Controller
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbHelper = require('db-helper')
const twoHourInMills = 2 * 60 * 1000 //2 * 60 * 60 * 1000
module.exports = class OrderController extends Controller {
	async getRefundApplyDetail() {
		let {
			applyId
		} = this.ctx.data
		if (!applyId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		try {
			let order = await this.service.order.getRefundApplyDetail({
				applyId
			})
			return {
				code: 200,
				result: order
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async calcRefundFee() {
		let {
			orderId,
			count
		} = this.ctx.data
		if (!orderId || !count || !parseInt(count) || parseInt(count) < 0) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		try {
			let order = await dbHelper.getById("t3ds-order", orderId)
			if (!order) {
				return {
					code: 500,
					msg: '订单不存在'
				}
			}
			let result = this.service.order.calcRefundFee({
				order,
				count
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}
	async getOrderRefundDetail() {
		let {
			orderId,
			userLocation
		} = this.ctx.data
		if (!orderId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		try {
			let order = await this.service.order.getOrderRefundDetail({
				orderId,
				userLocation
			})
			return {
				code: 200,
				result: order
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}
	async applyRefund() {
		let {
			orderId,
			reason,
			count,
			photos
		} = this.ctx.data
		if (!orderId || !reason || !count) {
			return {
				code: 500,
				msg: "参数错误"
			}
		}
		try {
			let res = await this.service.order.applyRefund({
				orderId,
				reason,
				photos: photos || [],
				count
			})
			return {
				code: 200,
				result: res
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async getMyOrders() {
		let {
			pageNum,
			pageSize,
			status,
			orderType,
			createStartTime,
			createEndTime,
			applyInvoice = false
		} = this.ctx.data
		console.log(orderType)
		try {
			let result = {
				code: 200,
				result: {
					total: 0,
					list: []
				}
			}
			let fun = orderType === 'goods' ? 'getGoodsOrderList' : 'getSubscribeOrderList'
			let page = await this.service.order[fun]({
				memberId: this.ctx.auth.uid,
				pageNum,
				pageSize,
				status,
				createStartTime,
				createEndTime,
				applyInvoice
			})
			result.result = page
			return result
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async getReceiptNames() {
		let {
			ticketId,
			giftId,
			orderId
		} = this.ctx.data
		try {
			let list = await this.service.order.getReceiptNames({
				uid: this.ctx.auth.uid,
				ticketId,
				orderId,
				giftId
			})
			return {
				code: 200,
				result: list
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	//用户端获取套票列表的接口
	async getReceiptList() {
		let {
			ticketId,
			orderId,
			giftId,
			name,
			status,
			pageNum,
			pageSize
		} = this.ctx.data
		try {
			let list = await this.service.order.getReceiptList({
				uid: this.ctx.auth.uid,
				ticketId,
				orderId,
				giftId,
				name,
				status,
				pageNum,
				pageSize
			})
			return {
				code: 200,
				result: list
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async createEvaluation() {
		let {
			orderId,
			score,
			description,
			photos = []
		} = this.ctx.data
		if (!orderId || !parseInt(score) || !description) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		try {
			await this.service.order.createEvaluation({
				orderId,
				score,
				description,
				photos
			})
			return {
				code: 200
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async cancelOrder() {
		const {
			orderId
		} = this.ctx.data
		if (!orderId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return this.service.order.cancelOrder(orderId)
	}

	async genOpenVipOrder() {
		const {
			vipCardId,
			payType
		} = this.ctx.data
		console.log(payType)
		let vipCard = await dbHelper.getById("t3ds-vip-card", vipCardId)
		if (!vipCard || !vipCard.onSell) {
			return {
				code: 500,
				msg: '会员卡不存在'
			}
		}
		return await this.service.order.genOpenVipOrder(vipCard, payType)
	}


	//开发调试,完成订单
	async updatePakcageState() {
		const {
			orderId,
			user
		} = this.ctx.data
		console.log("orderId", orderId)
		let packageInfo = await dbHelper.getById("t3ds-package", orderId)
		let data;
		let title;
		let total;
		if (packageInfo.type == 0) {
			//充值赠送余额
			data = {
				uid: user._id,
				storeIds: packageInfo.storeIds,
				storeId: packageInfo.storeId,
				packageAmount: packageInfo.packageTopupAmount + packageInfo.packageGiveAmount,
				endTime: packageInfo.endTime,
				createTime: Date.now(),
				closeRatio: packageInfo.closeRatio,
				type: packageInfo.type
			}
			title = '扫码充值'
			total = data.packageAmount
		} else {
			//充值直购优惠券
			data = {
				uid: user._id,
				storeIds: packageInfo.storeIds,
				storeId: packageInfo.storeId,
				discountCoupon: packageInfo.properties,
				endTime: packageInfo.endTime,
				createTime: Date.now(),
				closeRatio: packageInfo.closeRatio,
				type: packageInfo.type
			}
			title = '扫码直购优惠券'
			total = data.discountCoupon.length
		}

		//设置礼包
		await dbHelper.insert('t3ds-package-user', data)
		// 设置日志明细
		let log = {
			uid: user._id,
			packageTopupId: data._id,
			title: title,
			total: total,
			detailType: 0,
			createTime: Date.now()
		}
		await dbHelper.insert('t3ds-package-log', log)



	}


		//礼包订单
		//创建礼包订单
		async genPackageOrder() {
			const {
				packageId
			} = this.ctx.data
			console.log(packageId)
			let packageInfo = await dbHelper.getById("t3ds-package", packageId)
			console.log("packageInfo", packageInfo)
			if (!packageInfo) {
				return {
					code: 500,
					msg: '礼包不存在'
				}
			}
			return await this.service.order.genPackageOrder(packageInfo)
		}


	// 商品订单
	//创建商品订单
	async genGoodsOrder() {
		let {
			skuId,
			count,
			useBalance,
			shareManId,
			type
		} = this.ctx.data
		count = parseInt(count)
		if (!skuId || isNaN(count)) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return await this.service.order.genGoodsOrder(skuId, count, useBalance, shareManId, type)
	}
	async genGoodsOrderTt() {
		let {
			skuId,
			count,
			useBalance,
			shareManId,
			type
		} = this.ctx.data
		count = parseInt(count)
		if (!skuId || isNaN(count)) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return await this.service.order.genGoodsOrder(skuId, count, useBalance, shareManId, type)
	}

	// 生成头条担保支付订单
	async ttPayController() {
		let {
			params
		} = this.ctx.data
		return await this.service.order.ttPayService(params)
	}


	async ttPayRefundController() {
		let {
			out_order_no
		} = this.ctx.data
		// 支付的订单号和生成的退款单号
		return await this.service.order.ttPayRefundService(out_order_no, new Date().getTime().toString())
	}



	// 秒杀商品订单
	async genSeckillGoodsOrder() {
		let {
			skuId,
			count,
			useBalance,
			shareManId
		} = this.ctx.data
		count = parseInt(count)
		if (!skuId || isNaN(count)) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return await this.service.order.genSeckillGoodsOrder(skuId, count, useBalance, shareManId)
	}

	// 充值订单
	async genRechargeOrder() {
		let {
			payType,
			amount
		} = this.ctx.data
		amount = parseInt(amount)
		if (isNaN(amount)) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return await this.service.order.genRechargeOrder(payType, amount)
	}

	// 租借物品订单
	async genRentOrder() {
		let {
			goodsId,
			count
		} = this.ctx.data
		count = parseInt(count)
		if (isNaN(count) || count <= 0) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return this.service.order.genRentOrder(goodsId, count)
	}

	async genPayInfo() {
		let {
			provider,
			payType,
			orderId
		} = this.ctx.data

		if (!orderId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return await this.service.order.genPayInfo(payType, orderId)
	}

	async getOrderDetail() {
		let {
			id,
			userLocation,
			type
		} = this.ctx.data
		if (!id) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		if (userLocation) {
			if (isNaN(parseFloat(userLocation.latitude)) || isNaN(parseFloat(userLocation.longitude))) {
				userLocation = null
			}
		}
		return this.service.order.getOrderDetail(id, type, userLocation)
	}

	// 退出车队
	async exitMotorcade() {
		let {
			motorcadeId,
			orderId
		} = this.ctx.data
		if (!motorcadeId || !orderId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		return this.service.order.exitMotorcade(motorcadeId, orderId)
	}

	// 预约剧本杀订单 + 剧本杀续时订单
	async genSubscribeScriptOrder() {
		let {
			orderType,
			scriptId,
			maleCount,
			femaleCount,
			startTime,
			endTime,
			storeId,
			roomId,
			useBalance = false,
			allowGetOn = true, //当当前人数大于等于最低人数后，是否允许继续加人
			motorcadeId, // 车队id
			couponId, //优惠券id
			// buyCardId, //会员卡/折扣卡id
			shareManId,
			currentOrderId
		} = this.ctx.data

		if (!scriptId || isNaN(maleCount + femaleCount) || !startTime || !parseInt(startTime) || !endTime || !
			parseInt(endTime) || !storeId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}

		//方便测试，注释这里------------------------
		// if ((startTime < Date.now() + twoHourInMills) && orderType !== 'renewal') {
		// 	return {
		// 		code: 500,
		// 		msg: '请提前两小时预约'
		// 	}
		// }
		//方便测试，注释这里-------------------------
		// if ((endTime - startTime) < twoHourInMills) {
		// 	return {
		// 		code: 500,
		// 		msg: '间隔时间不能小于2小时'
		// 	}
		// }
		try {
			let result = await this.service.order.genSubscribeScriptOrder({
				orderType,
				scriptId,
				maleCount,
				femaleCount,
				startTime,
				endTime,
				storeId,
				roomId,
				useBalance,
				allowGetOn,
				motorcadeId,
				couponId, //优惠券id
				// buyCardId, //会员卡/折扣卡id
				shareManId,
				currentOrderId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	// 茶室订单 + 茶室续时订单
	async genTearoomOrder() {
		let {
			orderType,
			startTime,
			endTime,
			storeId,
			roomId,
			useBalance = false,
			couponId, //优惠券id
			// buyCardId, //会员卡/折扣卡id
			shareManId,
			tearoomOrderId // 当前茶室订单id
		} = this.ctx.data

		if (!startTime || !parseInt(startTime) || !endTime || !parseInt(endTime) || !storeId || !roomId) {
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		// if ((startTime < Date.now() + twoHourInMills) && orderType !== 'renewal') {
		// 	return {
		// 		code: 500,
		// 		msg: '请提前两小时预约'
		// 	}
		// }
		if ((endTime - startTime) < twoHourInMills) {
			return {
				code: 500,
				msg: '间隔时间不能小于2小时'
			}
		}

		return await this.service.order.genTearoomOrder({
			orderType,
			startTime,
			endTime,
			storeId,
			roomId,
			useBalance,
			couponId, //优惠券id
			// buyCardId, //会员卡/折扣卡id
			shareManId,
			tearoomOrderId // 当前茶室订单id
		})
	}

	// 更新未支付的预约订单
	async uptateUnpaidOrder() {
		let {
			orderType,
			couponId, //优惠券id
			startTime,
			endTime,
			scriptId,
			maleCount,
			femaleCount,
			roomId,
			useBalance = false,
			// buyCardId, //会员卡/折扣卡id
			shareManId,
			orderId
		} = this.ctx.data
		try {
			let result = await this.service.order.uptateUnpaidOrder({
				orderType,
				couponId, //优惠券id
				startTime,
				endTime,
				scriptId,
				maleCount,
				femaleCount,
				roomId,
				useBalance,
				// buyCardId, //会员卡/折扣卡id
				shareManId,
				orderId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	// 创建固定时间拼车订单
	async genThemeOrder() {
		let {
			skuId,
			themeId,
			maleCount,
			femaleCount,
			useBalance,
			shareManId,
			startTime,
			endTime,
			storeId,
			allowGetOn,
			motorcadeId
		} = this.ctx.data
		try {
			if (!skuId || !themeId || !startTime || !endTime || !storeId) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.genThemeOrder({
				skuId,
				themeId,
				maleCount,
				femaleCount,
				useBalance,
				shareManId,
				startTime,
				endTime,
				storeId,
				allowGetOn,
				motorcadeId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	//获取当前用户当前未锁定规格票券的数量
	async getTicketCount() {
		let {
			skuId
		} = this.ctx.data
		try {
			if (!skuId) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.getTicketCount({
				skuId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	//获取当前规格的车队列表
	async getSkuMotorcadeList() {
		let {
			skuId,
			themeId
		} = this.ctx.data
		try {
			if (!skuId || !themeId) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.getSkuMotorcadeList({
				skuId,
				themeId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	//通过订单ID获取车队订单的详细信息
	async getMotorcadeDetail() {
		let {
			orderId
		} = this.ctx.data
		try {
			if (!orderId) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.getMotorcadeDetail({
				orderId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	//用户点击已到店（结束车队，结算押金）
	async getToStore() {
		let {
			orderId,
			userLocation
		} = this.ctx.data
		try {
			if (!orderId || !userLocation) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.getToStore({
				orderId,
				userLocation
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}

	//通过车队ID获取车队的详细信息及门店信息
	async getMotorcadeAndStore() {
		let {
			motorcadeId
		} = this.ctx.data
		try {
			if (!motorcadeId) {
				return {
					code: 500,
					msg: '参数错误'
				}
			}
			let result = await this.service.order.getMotorcadeAndStore({
				motorcadeId
			})
			return {
				code: 200,
				result
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message || e
			}
		}
	}
}